const HttpApi = {
    storeKey: "X-AUTOCODE-TOKEN",
    instance: axios.create({
        timeout: 300000
    }),

    getInstance: function () {
        let that = this;
        this.instance.interceptors.request.use(config => {
            // 更新 token
            config.headers[that.storeKey] = sessionStorage.getItem(that.storeKey)
            return config;
        });
        return this.instance;
    },

    login: function (param, callback) {
        HttpApi.openLoading();
        let that = this;
        this.getInstance().post("/platform/login", param).then(function (res) {
            HttpApi.closeLoading();
            if (res.data.code === 1) {
                sessionStorage.setItem(that.storeKey, res.data.data.token);
                sessionStorage.setItem("userName", res.data.data.username);
                callback(res.data.data);
            } else {
                Vue.prototype.$alert(res.data.msg);
            }
        }).catch(function (err) {
            HttpApi.closeLoading();
            if (err.response && err.response.status === 500) {
                Vue.prototype.$alert(err.response.data);
            } else {
                Vue.prototype.$alert(err);
            }
        });
    },

    relogin: function (param, callback) {
        let that = this;
        HttpApi.openLoading();
        this.getInstance().post("/platform/relogin", param)
            .then(function (res) {
                if (res.data.code === 1) {
                    sessionStorage.setItem(that.storeKey, res.data.data.token);
                    callback(true);
                } else if (res.data.code === 0) {
                    callback(false, res.data.msg);
                }
                HttpApi.closeLoading();
            });
    },

    checkLogin: function (callback) {
        let token = sessionStorage.getItem(this.storeKey);
        if (token == null || token === "") {
            window.location.href = "/platform/forLogin";
        } else {
            this.getInstance().post("/platform/checkToken", {})
                .then(function (res) {
                    if (res.data.code === 0) {
                        window.location.href = "/platform/forLogin";
                    } else {
                        sessionStorage.setItem("userName", res.data.data.userName);
                        sessionStorage.setItem("realName", res.data.data.realName);
                        sessionStorage.setItem("orgCode", res.data.data.orgCode);
                        sessionStorage.setItem("orgName", res.data.data.orgName);
                        sessionStorage.setItem("deptList", JSON.stringify(res.data.data.deptList));
                        callback(res.data.data);
                    }
                }).catch(function () {
                window.location.href = "/platform/forLogin";
            });
        }
    },

    get: function (url, param, callback) {
        this.getInstance().get(url, param).then(function (res) {
            if (res.data.code === 7) {
                let _parentWin = window.top;
                _parentWin.relogin();
            } else if (res.data.code === 1) {
                callback(res.data.data);
            } else {
                Vue.prototype.$alert(res.data.msg);
            }
        }).catch(function (err) {
            if (err.response && err.response.status === 500) {
                Vue.prototype.$alert(err.response.data);
            } else {
                Vue.prototype.$alert(err);
            }
        })
    },

    post: function (url, param, callback) {
        HttpApi.openLoading();
        HttpApi.post2(url, param, callback);
    },

    post2: function (url, param, callback) {
        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        this.getInstance().post(url, param)
            .then(function (res) {
                HttpApi.closeLoading();
                if (res.data.code === 7) {
                    let _parentWin = window.top;
                    _parentWin.relogin();
                } else if (res.data.code === 1) {
                    callback(res.data.data);
                } else {
                    Vue.prototype.$alert(res.data.msg);

                }
            }).catch(function (err) {
            HttpApi.closeLoading();
            if (err.response && err.response.status === 500) {
                Vue.prototype.$alert(err.response.data);
            } else {
                //Error: Network Error
                Vue.prototype.$alert(err);
            }
        });
    },

    postConfirm: function (url, param, callback) {
        Vue.prototype.$confirm('确定执行此操作?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            HttpApi.post(url, param, function (res) {
                callback(res);
            });
        }).catch(function () {

        });
    },

    postConfirm2: function (msg, url, param, callback) {
        Vue.prototype.$confirm(msg, '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            HttpApi.post(url, param, function (res) {
                callback(res);
            });
        }).catch(function () {

        });
    },

    postPasswordConfirm: function (url, param, callback) {
        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        let that = this;
        Vue.prototype.$prompt('', '请输入密码', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'password',
            inputErrorMessage: '密码不能为空',
            inputValidator: function (value) {
                return !(value == null || value === "");
            }
        }).then(({value}) => {
            HttpApi.openLoading();
            that.getInstance().post(url, param, {
                headers: {
                    'checkPassword': value
                }
            }).then(function (res) {
                    HttpApi.closeLoading();
                    if (res.data.code === 7) {
                        let _parentWin = window.top;
                        _parentWin.relogin();
                    } else {
                        if (res.data.code === 1) {
                            callback(res.data.data);
                        } else {
                            Vue.prototype.$alert(res.data.msg);
                        }
                    }
            }).catch(function (err) {
                HttpApi.closeLoading();
                if (err.response && err.response.status === 500) {
                    Vue.prototype.$alert(err.response.data);
                } else {
                    //Error: Network Error
                    Vue.prototype.$alert(err);
                }
            });
        }).catch(() => {

        });
    },

    postTextConfirm: function (url, title,param, callback) {
        if (title == null || title === "") {
            title = "操作原因"
        }

        Vue.prototype.$prompt('', title, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputErrorMessage: title+'不能为空',
            inputValidator: function (value) {
                return !(value == null || value === "");
            }
        }).then(({value}) => {
            param.reason = value;
            HttpApi.post(url,param,function (res) {
                callback(res);
            });
        }).catch(() => {

        });
    },


    upload: function (file, callback) {
        let uploadUrl = file.action;
        if (!uploadUrl.startsWith("/")) {
            uploadUrl = "/" + uploadUrl;
        }
        const formData = new FormData();
        formData.append("file", file.file);
        for (let key in file.data) {
            formData.append(key, file.data[key]);
        }
        HttpApi.openLoading();
        this.getInstance().post(uploadUrl, formData, {"Content-Type": "multipart/form-data"}).then(function (res) {
            HttpApi.closeLoading();
            if (res.data.code === 7) {
                let _parentWin = window.top;
                _parentWin.relogin();
            } else if (res.data.code === 1) {
                callback(res.data.data);
                Vue.prototype.$message.success("上传成功");
            } else {
                Vue.prototype.$alert(res.data.msg);
            }
        }).catch(function (err) {
            HttpApi.closeLoading();
            if (err.response && err.response.status === 500) {
                Vue.prototype.$alert(err.response.data);
            } else {
                Vue.prototype.$alert(err);
            }
        });
    },

    downLoad: function (url, param) {
        HttpApi.download(url, param);
    },

    download: function (url, param) {
        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        HttpApi.openLoading();
        this.getInstance().post(url, param, {responseType: 'blob'})
            .then(function (res) {
                HttpApi.closeLoading();
                const {data, headers} = res;
                let fileName = headers['file-name'];
                if (headers['content-type'] == 'application/json') {
                    const reader = new FileReader();
                    reader.readAsText(data);
                    reader.onload = () => {
                        try {
                            Vue.prototype.$alert(reader.result);
                        } catch (error) {
                            Vue.prototype.$alert(error);
                        }
                    }
                } else {
                    const blob = new Blob([data], {type: headers['content-type']});
                    let dom = document.createElement('a');
                    let url = window.URL.createObjectURL(blob);
                    dom.href = url;
                    dom.download = decodeURI(fileName);
                    dom.style.display = 'none';
                    document.body.appendChild(dom);
                    dom.click();
                    dom.parentNode.removeChild(dom);
                    window.URL.revokeObjectURL(url);
                }
            }).catch(function (err) {
            HttpApi.closeLoading();
            if (err.response && err.response.status === 500) {
                if (err.response.data.type == 'application/json') {
                    const reader = new FileReader();
                    reader.readAsText(err.response.data);
                    reader.onload = () => {
                        try {
                            Vue.prototype.$alert(reader.result);
                        } catch (error) {
                            Vue.prototype.$alert(error);
                        }
                    }
                }
            } else {
                Vue.prototype.$alert(err);
            }
        });
    },

    downloadFile: function (fileId) {
        let url = "/autocode/fileProvider/downLoad/" + fileId;
        HttpApi.download(url, {});
    },
    downLoadFile: function (fileId) {
        let url = "/autocode/fileProvider/downLoad/" + fileId;
        HttpApi.download(url, {});
    },
    //预览
    preview: function (fileId) {
        window.open('/autocode/fileProvider/filePreview/' + fileId);
    },

    //打印
    printLabel: function (labeCode, param) {
        let requestParam = "";
        for (let key in param) {
            // 判断属性是否是对象自身的属性而非继承的属性
            if (param.hasOwnProperty(key)) {
                if (requestParam === "") {
                    requestParam = requestParam + "?" + key + "=" + param[key];
                } else {
                    requestParam = requestParam + "&" + key + "=" + param[key];
                }
            }
        }
        let url = "/sysSetting/sysLabel/print/" + labeCode + requestParam;
        window.open(url);
    },

    printRecord: function (param) {
        let requestParam = "";
        for (let key in param) {
            // 判断属性是否是对象自身的属性而非继承的属性
            if (param.hasOwnProperty(key)) {
                if (requestParam === "") {
                    requestParam = requestParam + "?" + key + "=" + param[key];
                } else {
                    requestParam = requestParam + "&" + key + "=" + param[key];
                }
            }
        }
        let url = "/sysSetting/sysRecord/print" + requestParam;
        window.open(url);
    },

    export: function (param) {
        let url = "/excel/excelTemplate/export";
        HttpApi.download(url, param);
    },

    deleteFile: function (fileId, callback) {
        let url = "/autocode/fileProvider/deleteFile/" + fileId;
        HttpApi.postConfirm(url, {}, function (res) {
            callback(res);
        });
    },
    batchDeleteFile: function (fileIds, callback) {
        let url = "/autocode/fileProvider/batchDeleteFile";
        HttpApi.postConfirm(url, fileIds, function (res) {
            callback(res);
        });
    },

    saveProvider: function (tableCode, param, callback) {
        HttpApi.openLoading();
        let url = "/autocode/saveProvider/" + tableCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        });
    },

    saveProviderConfirm: function (tableCode, param, callback) {
        Vue.prototype.$confirm('确定执行此操作?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            HttpApi.saveProvider(tableCode, param, callback);
        }).catch(function () {

            }
        );

    },

    saveBatchProvider: function (tableCode, array, callback) {
        HttpApi.openLoading();
        let url = "/autocode/saveBatchProvider/" + tableCode;
        HttpApi.post(url, array, function (res) {
            callback(res);
        });
    },

    updateProvider: function (tableCode, fieldName, param, callback) {
        if (!param.id || param.id === '') {
            Vue.prototype.$alert("没有ID主键，不能进行数据更新");
            return;
        }
        let url = "/autocode/updateProvider/" + tableCode + "/" + fieldName;
        HttpApi.post2(url, param, function (res) {
            callback(res);
        });
    },

    updateProviderConfirm: function (tableCode, fieldName, param, callback) {
        Vue.prototype.$confirm('确定执行此操作?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            HttpApi.openLoading();
            HttpApi.updateProvider(tableCode, fieldName, param, callback);
        }).catch(function () {

            }
        );
    },

    delProvider: function (tableCode, param, callback) {
        let url = "/autocode/delProvider/" + tableCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        })
    },

    delProviderConfirm: function (tableCode, param, callback) {
        Vue.prototype.$confirm('此操作将永久删除, 是否继续?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            HttpApi.delProvider(tableCode, param, callback);
        }).catch(function () {

            }
        );
    },

    delBatchProviderConfirm: function (tableCode, param, callback) {
        let paramArray = {};
        let array = [];
        let dl = param.length;
        for (let i = 0; i < dl; i++) {
            array.push(param[i].id);
        }
        paramArray.id = array;
        Vue.prototype.$confirm('此操作将永久删除, 是否继续?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(function () {
            HttpApi.delProvider(tableCode, paramArray, callback);
        }).catch(function () {

            }
        );
    },

    editProvider: function (tableCode, param, callback) {
        let url = "/autocode/editProvider/" + tableCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        })
    },

    queryObject: function (tableCode, param, callback) {
        let url = "/autocode/queryObject/" + tableCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        });
    },

    queryArray: function (tableCode, param, callback) {
        let url = "/autocode/queryArray/" + tableCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        });
    },

    queryPaging: function (tableCode, pagingData, param, callback) {
        let url = "/autocode/queryPagingArray/" + tableCode;
        let pagingParam = {};
        pagingParam.pagingData = pagingData;
        pagingParam.param = param;
        HttpApi.post(url, pagingParam, function (res) {
            pagingData.currentPage = res.pagingData.currentPage;
            pagingData.pageSize = res.pagingData.pageSize;
            pagingData.pageCount = res.pagingData.pageCount;
            pagingData.total = res.pagingData.total;
            callback(res.data);
        });
    },

    queryTree: function (tableCode, param, callback) {
        let url = "/autocode/queryTreeArray/" + tableCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        });
    },

    queryDs: function (dataSourceCode, param, callback) {
        let url = "/autocode/queryDs/" + dataSourceCode;
        HttpApi.post(url, param, function (res) {
            callback(res);
        });
    },

    queryDS: function (dataSourceCode, param, callback) {
        HttpApi.queryDs(dataSourceCode, param, callback);
    },


    submitForm: function (url, formData, callback) {
        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        HttpApi.openLoading();
        this.getInstance().post(url, formData, {"Content-Type": "multipart/form-data"}).then(function (res) {
            HttpApi.closeLoading();
            if (res.data.code === 7) {
                let _parentWin = window.top;
                _parentWin.relogin();
            } else if (res.data.code === 1) {
                callback(res.data.data);
            } else {
                Vue.prototype.$alert(res.data.msg);
            }
        }).catch(function (err) {
            HttpApi.closeLoading();
            if (err.response && err.response.status === 500) {
                Vue.prototype.$alert(err.response.data);
            } else {
                Vue.prototype.$alert(err);
            }
        });
    },

    dictOptions: function (param, callback) {
        let url = "/autocode/dictProvider/options";
        this.getInstance().post(url, param)
            .then(function (res) {
                HttpApi.closeLoading();
                if (res.data.code === 1) {
                    callback(res.data.data);
                }
            }).catch(function (err) {
            HttpApi.closeLoading();
        });
    },
    customOptions: function (dict, param, callback) {
        let url = "/autocode/customDictProvider/" + dict;
        HttpApi.post2(url, param, function (res) {
            callback(res);
        })
    },
    pageDialog: function (url, title) {
        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        let newUrl = "/platform/page" + url;
        layer.open({
            type: 2,
            title: title,
            content: newUrl,
            maxmin: true,
            area: ['80%', '80%']
        })
    },

    wfSubmit: function (param, callback) {
        let url = "/platform/workflow/submit";
        HttpApi.post(url, param, callback);
    },

    wfSubmitConfirm: function (param, callback) {
        let url = "/platform/workflow/submit";
        HttpApi.postConfirm(url, param, callback);
    },

    openLoading: function () {
        window.apiloading = window.ELEMENT.Loading.service({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(196, 196, 196, 0.5)'
        });
    },

    closeLoading: function () {
        if (window.apiloading) {
            window.apiloading.close();
        }
    }
}
